package com.example.security.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author void
 * @date 2020/12/7 19:46
 * @desc
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * ANT模式使用？匹配任意单个字符，使用* 匹配0或任意数量的字符，
     * 使用**匹配0或者更多的目录。antMatchers（"/admin/api/**"）相当于匹配 了/admin/api/下的所有API
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**","/captcha").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable().formLogin().loginPage("/myLogin.html").loginProcessingUrl("/auth/form").permitAll()
                    .failureHandler(new MyAuthenticationFailureHandler())
                .and()
                //控制只允许同时一个用户登录
                .sessionManagement().maximumSessions(1).and();
        http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
